import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';

Effect<UserAccountState> buildEffect() {
  return combineEffects(<Object, Effect<UserAccountState>>{
    Lifecycle.initState: _initState,
    UserAccountAction.onSubmit: _onSubmit,
  });
}

void _initState(Action action, Context<UserAccountState> ctx) async {
  ctx.state.password = ctx.state.editingController.text = GlobalStore.store.getState().userInfo.password;
  ctx.dispatch(UserAccountActionCreator.onAction());
}

void _onSubmit(Action action, Context<UserAccountState> ctx) async {
  if (ctx.state.password != ctx.state.editingController.text) {
    CommonUtils.showWaitLoading(ctx.context);
    ResultData res;
    if (GlobalStore.store.getState().userInfo.isGsUser) {
      res = await CommonNetWork.updatePassword(
          ctx.state.password, ctx.state.editingController.text);
    }
    else {
      res = await CommonNetWork.staffUpdatePassword(
          ctx.state.password, ctx.state.editingController.text);
    }
    Navigator.pop(ctx.context);
    if (res.success) {
      ctx.state.userInfo.password = ctx.state.editingController.text;
      ctx.state.userInfo.mobile = ctx.state.userInfo.mobile;
      GlobalStore.store
          .dispatch(GlobalActionCreator.onUserLogin(ctx.state.userInfo));

      await CommonUtils.setPubDefaultValue(
          password: ctx.state.editingController.text);
      await CommonUtils.showAlertView(ctx.context, '修改成功');
      Navigator.pop(ctx.context);
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
  } else
    Navigator.pop(ctx.context);
}
